<template>
  <div>
    <div class="card" style="margin-bottom: 5px">
      <el-input clearable @clear="load" style="width: 260px;margin-right: 5px"  v-model="data.name" placeholder="请输入活动名称查询" :prefix-icon="Search"></el-input>
      <el-button type="primary" @click="load">查询</el-button>
      <el-button @click="reset">重置</el-button>
    </div>

    <div class="card" style="margin-bottom: 5px" v-if="data.user.role==='ADMIN'">
      <el-button type="danger" @click="delBatch">批量删除</el-button>
      <el-button type="primary" @click="handleAdd">新 增</el-button>
    </div>

    <div class="card" style="margin-bottom: 5px">
      <el-table :data="data.tableData" style="width: 100%" :header-cell-style="{color:'#333',backgroundColor:'#eaf4ff'}" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="name" label="活动名称"/>
        <el-table-column prop="descr" label="活动描述"/>
        <el-table-column prop="img" label="活动图片">
          <template #default="scope">
            <el-image v-if="scope.row.img" :src="scope.row.img" :preview-src-list="[scope.row.img]" :preview-teleported="true"
                      style="width: 40px;height: 40px;border-radius: 5px;display: block"/>
          </template>
        </el-table-column>
        <el-table-column prop="start" label="开始时间"/>
        <el-table-column prop="end" label="结束时间"/>
        <el-table-column prop="location" label="活动地点"/>
        <el-table-column prop="num" label="报名人数"/>
        <el-table-column prop="content" label="活动详情">
          <template #default="scope">
            <el-button size="small" type="primary" @click="view(scope.row.content)">查看内容</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="活动状态">
          <template #default="scope">
            <el-tag type="primary" v-if="scope.row.status==='未开始'">未开始</el-tag>
            <el-tag type="success" v-if="scope.row.status==='进行中'">进行中</el-tag>
            <el-tag type="danger" v-if="scope.row.status==='已结束'">已结束</el-tag>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="100">
          <template #default="scope">
            <el-button type="primary" icon="Edit" circle @click="handleEdit(scope.row)"></el-button>
            <el-button type="danger" icon="Delete" circle @click="del(scope.row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="card" style="margin-bottom: 5px">
      <el-pagination
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          :page-sizes="[5,10,20]"
          :total="data.total"
          layout="total,sizes, prev, pager, next,jumper"
          @current-change="load"
          @size-change="load"
      />
    </div>

    <el-dialog title="图书活动" v-model="data.formVisible"  width="50%" destroy-on-close>
      <el-form ref="formRef" :model="data.form" :rules="data.rules" label-width="80px" style="padding: 20px 30px 10px 0">
        <el-form-item prop="name" label="活动名称" >
          <el-input v-model="data.form.name" autocomplete="off" placeholder="请输入活动名称"/>
        </el-form-item>
        <el-form-item prop="descr" label="活动描述" >
          <el-input type="textarea" :row="3" v-model="data.form.descr" autocomplete="off" placeholder="请输入活动描述"/>
        </el-form-item>
        <el-form-item prop="img" label="活动图片" >
          <el-upload
              action="http://localhost:9999/files/upload"
              :headers="{ token:data.user.token }"
              :on-success="handleFileSuccess"
              list-type="picture"
          >
            <el-button type="primary">上传图片</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item prop="start" label="开始日期" >
          <el-date-picker
              style="width: 100%"
              v-model="data.form.start"
              type="date"
              placeholder="开始日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item prop="end" label="结束时间" >
          <el-date-picker
              style="width: 100%"
              v-model="data.form.end"
              type="date"
              placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item prop="location" label="活动地点" >
          <el-input v-model="data.form.location" autocomplete="off" placeholder="请输入活动地点"/>
        </el-form-item>
        <el-form-item prop="content" label="活动详情" >
          <div style="border: 1px solid #ccc; width: 100%">
            <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :mode="mode"
            />
            <Editor
                style="height: 500px; overflow-y: hidden;"
                v-model="data.form.content"
                :mode="mode"
                :defaultConfig="editorConfig"
                @onCreated="handleCreated"
            />
          </div>
        </el-form-item>
        <el-form-item prop="status" label="活动状态" >
          <el-select
              v-model="data.form.status"
              placeholder="活动状态"
              size="large"
              style="width: 240px"
          >
            <el-option
                v-for="item in ['未开始','进行中','已结束']"
                :key="item"
                :label="item"
                :value="item"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.formVisible = false">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="内容" v-model="data.viewVisible" width="50%" :close-on-click-modal="false" destroy-on-close>
      <div class="editor-content-view" style="padding: 20px" v-html="data.content"></div>
      <template #footer>
    <span class="dialog-footer">
      <el-button @click="data.viewVisible = false">关 闭</el-button>
    </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {Search} from "@element-plus/icons-vue";
import {reactive,onBeforeUnmount, ref, shallowRef} from "vue";
import request from "@/utils/request.js";
import {ElMessage, ElMessageBox} from "element-plus";
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

const formRef=ref()

const data=reactive({
  user:JSON.parse(localStorage.getItem('code_user')||"{}"),
  name:null,
  pageNum:1,
  pageSize:5,
  total:0,
  tableData:[],
  ids:[],
  form:{},
  viewVisible: false,
  content: null,
  formVisible:false,
  rules:{
    title:[
      {required:true,message:'请填写分类标题',trigger:'blur'},
    ]
  }
})

const load =()=>{
  request.get('/activity/selectPage',{
    params:{
      pageNum:data.pageNum,
      pageSize:data.pageSize,
      name:data.name
    }
  }).then(res=>{
    if(res.code==='200'){
      data.tableData=res.data?.list
      data.total=res.data?.total
    }else {
      ElMessage.error(res.msg)
    }
  })
}
load()

const handleAdd=()=>{
  data.form={}
  data.formVisible=true
}

const handleEdit=(row)=>{
data.form=JSON.parse(JSON.stringify(row))
  data.formVisible=true
}

const add=()=>{
  request.post('/activity/add',data.form).then(res=>{
    if (res.code==='200'){
      ElMessage.success('新增成功')
      data.formVisible=false
      load()
    }else {
      ElMessage.error(res.msg)
    }
  })
}

const update=()=>{
  request.put('/activity/update',data.form).then(res=>{
    if (res.code==='200'){
      ElMessage.success('更新成功')
      data.formVisible=false
      load()
    }else {
      ElMessage.error(res.msg)
    }
  })
}

const save=()=>{
formRef.value.validate(valid=>{
  if(valid){
    data.form.id?update():add()
  }
})
}

const del=(id)=>{
  ElMessageBox.confirm('删除后无法回复，确认删除吗？','删除确认',{type:'warning'}).then(res=>{
    request.delete('/activity/delete/'+id).then(res=> {
      if (res.code === '200') {
        ElMessage.success('删除成功')
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(err=>{})
}

const reset=()=>{
  data.name=null
  load()
}

const delBatch=()=>{
  if (!data.ids.length){
    ElMessage.warning("请选择数据")
    return
  }
  ElMessageBox.confirm('删除后无法回复，确认删除吗？','删除确认',{type:'warning'}).then(res=>{
    // 将 ids 参数以查询字符串的形式添加到 URL 中
    const url = `activity/delete/batch?ids=${data.ids.join(',')}`;
   request.delete(url).then(res=>{
     if (res.code === '200') {
       ElMessage.success('删除成功')
       load()
     } else {
       ElMessage.error(res.msg)
     }
   })
  }).catch(err=>{
    console.error(err)
  })
}
const handleSelectionChange=(rows)=>{
  data.ids=rows.map(v=>v.id)
}

const handleFileSuccess=(res)=>{
  data.form.img=res.data
}

/* wangEditor5 初始化开始 */

const editorRef=shallowRef()
const mode='default'
const editorConfig={ MENU_CONF:{} }

editorConfig.MENU_CONF['uploadImage']={
  headers:{
    token:data.user.token,
  },
  server:'http://localhost:9999/files/wang/upload',
  fieldName:'file'
}

onBeforeUnmount(()=>{
  const editor=editorRef.value
  if(editor==null) return
  editor.destroy()
})

const handleCreated=(editor)=>{
  editorRef.value=editor
}
/* wangEditor5 初始化结束 */


const view = (content) => {
  data.content = content
  data.viewVisible = true
}

</script>